﻿using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace template_dll
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public SqlConnection conn;

        public string nameAct = "";
        public string typeAct = "";
        public string typePrize = "";
        public DateTime dateStart = DateTime.Now.Date;
        public DateTime dateEnd = DateTime.Now.Date;
        public string destr = "";
        public int actionId = 0;
        public int typeActId = 0;
        public int typePrizeId = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            Form3 formNew = new Form3();
            try
            {
                formNew.conn = conn;
                formNew.nameForm = "Новая акция";
                if (formNew.ShowDialog() == DialogResult.OK)
                {
                    SqlStorProc.sp_params[] param = new SqlStorProc.sp_params[6];
                    param[0].name = "@actname";
                    param[0].value = formNew.nameAct;
                    param[1].name = "@acttype";
                    param[1].value = formNew.typeAct;
                    param[2].name = "@datestart";
                    param[2].value = formNew.dateStart;
                    param[3].name = "@dateend";
                    param[3].value = formNew.dateEnd;
                    param[4].name = "@destr";
                    param[4].value = formNew.destr;
                    param[5].name = "@prizetype";
                    if (formNew.typePrize > 0) param[5].value = formNew.typePrize;

                    new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ActionInsert", 30, param);
                    MessageBox.Show("Новая акция создана");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                formNew.Close();
                formNew = null;
                SelActions();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form3 formNew = new Form3();
            try
            {
                formNew.conn = conn;
                formNew.nameForm = "Редактирование акции";
                formNew.nameAct = dataGridView1[dataGridView1.Columns["Наименование"].Index, dataGridView1.CurrentRow.Index].Value.ToString();
                formNew.dateStart = Convert.ToDateTime(dataGridView1[dataGridView1.Columns["Дата начала"].Index, dataGridView1.CurrentRow.Index].Value);
                formNew.dateEnd = Convert.ToDateTime(dataGridView1[dataGridView1.Columns["Дата окончания"].Index, dataGridView1.CurrentRow.Index].Value);
                formNew.destr = Convert.ToBoolean(dataGridView1[dataGridView1.Columns["Вкл"].Index, dataGridView1.CurrentRow.Index].Value);
                formNew.typeAct = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД типа"].Index, dataGridView1.CurrentRow.Index].Value);
                if (dataGridView1[dataGridView1.Columns["ИД премии"].Index, dataGridView1.CurrentRow.Index].Value != DBNull.Value) formNew.typePrize = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД премии"].Index, dataGridView1.CurrentRow.Index].Value);
                int actId = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД акции"].Index, dataGridView1.CurrentRow.Index].Value);
                if (formNew.ShowDialog() == DialogResult.OK)
                {
                    SqlStorProc.sp_params[] param = new SqlStorProc.sp_params[6];
                    param[0].name = "@actname";
                    param[0].value = formNew.nameAct;
                    param[1].name = "@actid";
                    param[1].value = actId;
                    param[2].name = "@datestart";
                    param[2].value = formNew.dateStart;
                    param[3].name = "@dateend";
                    param[3].value = formNew.dateEnd;
                    param[4].name = "@destr";
                    param[4].value = formNew.destr;
                    param[5].name = "@prizetype";
                    if (formNew.typePrize > 0) param[5].value = formNew.typePrize;

                    new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ActionUpdate", 30, param);
                    MessageBox.Show("Акция изменена");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                formNew.Close();
                formNew = null;
                SelActions();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Отключить акцию?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    SqlStorProc.sp_params[] param = new SqlStorProc.sp_params[2];
                    param[0].name = "@destr";
                    param[0].value = true;
                    param[1].name = "@actid";
                    param[1].value = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД акции"].Index, dataGridView1.CurrentRow.Index].Value);
                    new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ActionUpdate", 30, param);
                    MessageBox.Show("Акция отключена");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                SelActions();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    if (MessageBox.Show("Внимание! Вся информация по этой акции будет удалена!\nУдалить?", "Удалить акцию?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        SqlStorProc.sp_params[] param = new SqlStorProc.sp_params[1];
                        param[0].name = "@actid";
                        param[0].value = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД акции"].Index, dataGridView1.CurrentRow.Index].Value);
                        new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_ActionDel", 30, param);
                        MessageBox.Show("Акция отключена");
                    }
                }
                else MessageBox.Show("Не выбрана ни одна акция");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                SelActions();
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            SelActions();
        }

        void SelActions()
        {
            try
            {
                int sortCol = -1;
                try
                {
                    if (dataGridView1.SortedColumn.Index > -1) sortCol = dataGridView1.SortedColumn.Index;
                }
                catch(Exception)
                {
                }

                dataGridView1.DataSource = null;
                
                SqlStorProc.sp_params[] sp = new SqlStorProc.sp_params[0];
                dataGridView1.DataSource = new SqlStorProc().SqlProcExecWithQueryOneTable(conn, "pas_Actions_ActionSel", 30, sp).DefaultView;
                if (sortCol == -1) dataGridView1.Sort(dataGridView1.Columns["Наименование"], ListSortDirection.Ascending);
                else dataGridView1.Sort(dataGridView1.Columns[sortCol], ListSortDirection.Ascending);
                HideShowRows();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            HideShowRows();
        }

        private void HideShowRows()
        {
            if (dataGridView1.RowCount > 0)
            {
                CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
                cm.SuspendBinding();
                foreach (DataGridViewRow r in dataGridView1.Rows)
                {
                    r.Visible = true;
                    if (!Regex.Match(Convert.ToString(dataGridView1[dataGridView1.SortedColumn.Name, r.Index].Value), textBox1.Text, RegexOptions.IgnoreCase).Success)
                        r.Visible = false;
                }
                cm.ResumeBinding();
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                nameAct = dataGridView1[dataGridView1.Columns["Наименование"].Index, e.RowIndex].Value.ToString();
                typeAct = dataGridView1[dataGridView1.Columns["Тип акции"].Index, e.RowIndex].Value.ToString();
                dateStart = Convert.ToDateTime(dataGridView1[dataGridView1.Columns["Дата начала"].Index, e.RowIndex].Value);
                dateEnd = Convert.ToDateTime(dataGridView1[dataGridView1.Columns["Дата окончания"].Index, e.RowIndex].Value);
                destr = dataGridView1[dataGridView1.Columns["Состояние"].Index, e.RowIndex].Value.ToString();
                actionId = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД акции"].Index, e.RowIndex].Value);
                typeActId = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД типа"].Index, e.RowIndex].Value);
                if (dataGridView1[dataGridView1.Columns["ИД премии"].Index, e.RowIndex].Value != DBNull.Value)
                {
                    typePrize = dataGridView1[dataGridView1.Columns["Вид премирования"].Index, e.RowIndex].Value.ToString();
                    typePrizeId = Convert.ToInt32(dataGridView1[dataGridView1.Columns["ИД премии"].Index, e.RowIndex].Value);
                }
                this.DialogResult = DialogResult.OK;
            }
        }
    }
}
